package org.smarthings.scripting;

import java.util.ArrayList;
import java.util.List;

import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

public class ScriptEngineManagerDelegate extends ScriptEngineManager {

	private final List<ScriptEngineFactory> factories = new ArrayList<ScriptEngineFactory>();

	public ScriptEngineManagerDelegate(ClassLoader classLoader) {
		super(classLoader);
	}

	public ScriptEngineManagerDelegate() {
		super();
	}

	@Override
	public List<ScriptEngineFactory> getEngineFactories() {
		List<ScriptEngineFactory> baseFactories = super.getEngineFactories();

		List<ScriptEngineFactory> result = new ArrayList<ScriptEngineFactory>();
		result.addAll(factories);
		result.addAll(baseFactories);
		return result;
	}

	public void registerScriptEngineFactory(ScriptEngineFactory factory) {
		for (Object ext : factory.getExtensions()) {
			registerEngineExtension((String) ext, factory);
		}

		for (Object mime : factory.getMimeTypes()) {
			registerEngineMimeType((String) mime, factory);
		}

		for (Object name : factory.getNames()) {
			registerEngineName((String) name, factory);
		}

		factories.add(factory);
	}

}
